<?php

namespace Index\Controller;

use Think\Controller;
use Index\ViewModel;
use Index\Service;

/**
 * 说明：财务管理控制器
 * 作者：王楠
 * 创建日期：2017-09-15
 */
class FinanceController extends CommonController
{

    public function balanceloglist()
    {
        $state_enum = getenumbykey('balancelog_state');
        $state_arr = getarrbyenum($state_enum);
        $type_enum = getenumbykey('balancelog_type');
        $type_arr = getarrbyenum($type_enum);
        $toggle_enum = getenumbykey('balancelog_toggle');
        $toggle_arr = getarrbyenum($toggle_enum);
        $begintime = trim(I('txtbegintime'));
        $endtime = trim(I('txtendtime'));
        $keyword = trim(I('txtkeyword'));
        $state = trim(I('ddlstate'));
        $type = trim(I('ddltype'));
        $toggle = trim(I('ddltoggle'));
        $searchtype = trim(I('hidsearchtype'));
        $user_uid = I('uid');
        $app_code = $this->app_code;
        $login_type = $this->login_type;
        $admin_uid = $this->admin_uid;
        $is_agent_self = (int)($login_type == '2' && !empty($user_uid));
        switch ($searchtype) {
            case '1':
                if (!empty($toggle)) {
                    $type_enum_bak = array();
                    foreach ($type_enum as $key => $value) {
                        if ($toggle == '1') {
                            if ($key == '2' || $key == '3') {
                                continue;
                            }
                        }
                        if ($toggle == '2') {
                            if ($key == '1') {
                                continue;
                            }
                        }
                        $type_enum_bak[$key] = $value;
                    }
//		    $type_arr = getarrbyenum($type_enum_bak);
                    $value = $type_enum_bak[$type];
                    $type = empty($value) ? '0' : $type;
                }
                break;
            case '2':
                if (!empty($type)) {
                    if ($toggle == '1') {
                        if ($type == '2' || $type == '3') {
                            $toggle = '0';
                        }
                    }
                    if ($toggle == '2') {
                        if ($type == '1') {
                            $toggle = '0';
                        }
                    }
                }
                break;
            default:
                break;
        }
        $map = array('_complex' => '1=1');
        $appcode = trim(I('ddlapp'));

	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    }
	}
        if ($login_type == '2') {
            if (!empty($user_uid)) {
                $map['user_uid'] = $user_uid;
            } else {
                $map['agent_uid'] = $admin_uid;
            }
        }
        if (!empty($toggle)) {
            $map['toggle'] = $toggle;
        }
        if (!empty($type)) {
            $map['type'] = $type;
        }
        if (!empty($state)) {
            $map['state'] = $state;
        }
        if (!empty($begintime) || !empty($endtime)) {
            if (!empty($begintime) && !empty($endtime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
            } else if (!empty($begintime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
            } else if (!empty($endtime)) {
                $map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
            }
        }
        if (!empty($keyword)) {
            $where['chat_balancelog.order_no'] = array('eq', $keyword);
            $where['chat_balancelog.content'] = array('like', '%' . $keyword . '%');
            $where['chat_userinfo.user_id'] = array('eq', $keyword);
            $where['chat_userinfo.user_phone'] = array('like', '%' . $keyword . '%');
            $where['chat_userinfo.user_name'] = array('like', '%' . $keyword . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $viewModel = new ViewModel\BalancelogViewModel();
        $total = $viewModel->where($map)->count();
        $row = '10';
        $page = new Service\PageService($total, $row);
        $fpage = $page->fpage();
        $field = array(
            'id', 'user_uid', 'order_no', 'money', 'balance', 'ratio', 'state', 'type', 'toggle', 'content', 'ctime', 'user_id', 'user_logo', 'user_name', 'user_sex', 'user_phone'
        );
        $data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc')->select();
        foreach ($data as $key => $value) {
            $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
            $data[$key]['type_text'] = $type_enum[$data[$key]['type']];
            $data[$key]['toggle_text'] = $toggle_enum[$data[$key]['toggle']];
            $data[$key]['money_in_text'] = $data[$key]['toggle'] == '1' ? '' : (int)$data[$key]['money'];
            $data[$key]['money_out_text'] = $data[$key]['toggle'] == '1' ? (int)$data[$key]['money'] : '';
            $data[$key]['balance_text'] = (int)$data[$key]['balance'];
            $user_info = $this->app_name2.'号：' . $data[$key]['user_id'] . '<br />用户昵称：' . $data[$key]['user_name'] . '<br />手机号码：' . $data[$key]['user_phone'];
            $data[$key]['user_info'] = $user_info;
            $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
        }
        $search = array('appsel' => $appcode, 'statesel' => $state, 'typesel' => $type, 'togglesel' => $toggle, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
        $this->assign(array(
            'login_type' => $login_type,
            'is_agent_self' => $is_agent_self,
            'data' => $data,
            'fpage' => $fpage,
            'total' => $total,
            'statearr' => $state_arr,
            'typearr' => $type_arr,
            'togglearr' => $toggle_arr,
            'search' => $search,
            'app_code' => $app_code,
            'apparr' => $this->getapplist()
        ));
        $this->display();
    }

    public function shareloglist()
    {
        $state_enum = getenumbykey('balancelog_state');
        $state_arr = getarrbyenum($state_enum);
        $begintime = trim(I('txtbegintime'));
        $endtime = trim(I('txtendtime'));
        $keyword = trim(I('txtkeyword'));
        $state = trim(I('ddlstate'));
        $user_uid = I('uid');
        $app_code = $this->app_code;
        $login_type = $this->login_type;
        $admin_uid = $this->admin_uid;
        $is_agent_self = (int)($login_type == '2' && !empty($user_uid));
        $map = array('_complex' => '1=1');
        $map['app_flag'] = $app_code;
        if ($login_type == '2') {
            if (!empty($user_uid)) {
                $map['user_uid'] = $user_uid;
            } else {
                $map['agent_uid'] = $admin_uid;
            }
        }
        if (!empty($state)) {
            $map['state'] = $state;
        }
        if (!empty($begintime) || !empty($endtime)) {
            if (!empty($begintime) && !empty($endtime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
            } else if (!empty($begintime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
            } else if (!empty($endtime)) {
                $map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
            }
        }
        if (!empty($keyword)) {
            $where['a.orderNo'] = array('eq', $keyword);
            $where['a.content'] = array('like', '%' . $keyword . '%');
            $where['c.id'] = array('eq', $keyword);
            $where['b.account'] = array('like', '%' . $keyword . '%');
            $where['c.nickname'] = array('like', '%' . $keyword . '%');
            $where['e.id'] = array('eq', $keyword);
            $where['d.account'] = array('like', '%' . $keyword . '%');
            $where['e.nickname'] = array('like', '%' . $keyword . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $model = M('chat_sharelog');
        $total = $model->alias('a')
            ->join('left join chat_useraccount b on a.user_uid=b.user_uid')
            ->join('left join chat_userinfo c on a.user_uid=c.user_uid')
            ->join('left join chat_useraccount d on a.user_uid_share=d.user_uid')
            ->join('left join chat_userinfo e on a.user_uid_share=e.user_uid')
            ->where($map)
            ->count();
        $row = '10';
        $page = new Service\PageService($total, $row);
        $fpage = $page->fpage();
        $data = $model->alias('a')
            ->field('a.id AS id,a.uId AS user_uid,a.orderNo AS order_no,a.money AS money,a.balance AS balance,a.ratio AS ratio,a.state AS state,a.content AS content,a.ctime AS ctime, b.account as phone, c.id as user_id, c.logo as user_logo, c.nickname as user_name, c.sex as user_sex, d.account as phone2, e.id as user_id2, e.logo as user_logo2, e.nickname as user_name2, e.sex as user_sex2')
            ->join('left join chat_useraccount b on a.user_uid=b.user_uid')
            ->join('left join chat_userinfo c on a.user_uid=c.user_uid')
            ->join('left join chat_useraccount d on a.user_uid_share=d.user_uid')
            ->join('left join chat_userinfo e on a.user_uid_share=e.user_uid')
            ->where($map)
            ->limit($page->listfirst, $page->listRows)
            ->order('ctime desc')
            ->select();
        foreach ($data as $key => $value) {
            $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
            $data[$key]['money_text'] = (int)$data[$key]['money'];
            $data[$key]['balance_text'] = (int)$data[$key]['balance'];
            $user_info = $this->app_name2.'号：' . $data[$key]['user_id'] . '<br />用户昵称：' . $data[$key]['user_name'] . '<br />手机号码：' . $data[$key]['phone'];
            $data[$key]['user_info'] = $user_info;
            $user_info2 = $this->app_name2.'号：' . $data[$key]['user_id2'] . '<br />用户昵称：' . $data[$key]['user_name2'] . '<br />手机号码：' . $data[$key]['phone2'];
            $data[$key]['user_info2'] = $user_info2;
            $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
        }
        $search = array('appsel' => $appcode, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
        $this->assign(array(
            'login_type' => $login_type,
            'is_agent_self' => $is_agent_self,
            'data' => $data,
            'fpage' => $fpage,
            'total' => $total,
            'statearr' => $state_arr,
            'search' => $search,
            'app_code' => $app_code,
            'apparr' => $this->getapplist()
        ));
        $this->display();
    }

    public function rechargelist()
    {
        $type_enum = getenumbykey('recharge_type');
        $type_arr = getarrbyenum($type_enum);
        $state_enum = getenumbykey('recharge_state');
        $state_arr = getarrbyenum($state_enum);
        $type = trim(I('ddltype'));
        $state = trim(I('ddlstate'));
        $begintime = trim(I('txtbegintime'));
        $endtime = trim(I('txtendtime'));
        $keyword = trim(I('txtkeyword'));
        $app_code = $this->app_code;
        $login_type = $this->login_type;
        $admin_uid = $this->admin_uid;
        $map = array('_complex' => '1=1');
        $appcode = trim(I('ddlapp'));

	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    }
	}
        if ($login_type == '2') {
            $map['agent_uid'] = $admin_uid;
        }
        if (!empty($type)) {
            $map['type'] = $type;
        }
        if (!empty($state)) {
            $map['state'] = $state;
        }
        if (!empty($begintime) || !empty($endtime)) {
            if (!empty($begintime) && !empty($endtime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
            } else if (!empty($begintime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
            } else if (!empty($endtime)) {
                $map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
            }
        }
        if (!empty($keyword)) {
            $where['chat_recharge.order_no'] = array('eq', $keyword);
            $where['chat_userinfo.user_id'] = array('eq', $keyword);
            $where['chat_userinfo.user_phone'] = array('like', '%' . $keyword . '%');
            $where['chat_userinfo.user_name'] = array('like', '%' . $keyword . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $viewModel = new ViewModel\RechargeViewModel();
        $total = $viewModel->where($map)->count();
        $row = '10';
        $page = new Service\PageService($total, $row);
        $fpage = $page->fpage();
        $field = array(
            'id', 'user_uid', 'order_no', 'money', 'ratio', 'state', 'type', 'ctime', 'user_id', 'user_logo', 'user_name', 'user_sex', 'user_phone'
        );
        $data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc')->select();
        foreach ($data as $key => $value) {
//	    $data[$key]['money_text'] = (int) $data[$key]['money'];
            $data[$key]['money_text'] = '金币 ' . sprintf('%.2f', ((int)$data[$key]['money'] * (int)$data[$key]['ratio'])) . '<br /><label style="color:#ccc;">人民币 ' .(int)$data[$key]['money']  . '</label>';
            $data[$key]['type_text'] = $type_enum[$data[$key]['type']];
            $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
            $user_info = $this->app_name2.'号：' . $data[$key]['user_id'] . '<br />用户昵称：' . $data[$key]['user_name'] . '<br />手机号码：' . $data[$key]['user_phone'];
            $data[$key]['user_info'] = $user_info;
            $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
        }
        $search = array('appsel' => $appcode, 'typesel' => $type, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
        $this->assign(array(
            'data' => $data,
            'fpage' => $fpage,
            'total' => $total,
            'typearr' => $type_arr,
            'statearr' => $state_arr,
            'search' => $search,
            'app_code' => $app_code,
            'apparr' => $this->getapplist()
        ));
        $this->display();
    }

    public function withdrawlist()
    {
        $type_enum = getenumbykey('withdrawals_type');
        $type_arr = getarrbyenum($type_enum);
        $state_enum = getenumbykey('withdrawals_state');
        $state_arr = getarrbyenum($state_enum);
        $money_type = trim(I('type', '1'));
        $type = trim(I('ddltype'));
        $state = trim(I('ddlstate'));
        $begintime = trim(I('txtbegintime'));
        $endtime = trim(I('txtendtime'));
        $keyword = trim(I('txtkeyword'));
        $app_code = $this->app_code;
        $login_type = $this->login_type;
        $admin_uid = $this->admin_uid;
        $map = array('_complex' => '1=1');
        $appcode = trim(I('ddlapp'));
	if (!empty($app_code)) {
	    $map['app_flag'] = $app_code;
	} else {
	    if (!empty($appcode)) {
		$map['app_flag'] = $appcode;
	    }
	}
        $map['money_type'] = $money_type;
        if ($login_type == '2') {
            $map['agent_uid'] = $admin_uid;
        }
        if (!empty($type)) {
            $map['type'] = $type;
        }
        if (!empty($state)) {
            $map['state'] = $state;
        }
        if (!empty($begintime) || !empty($endtime)) {
            if (!empty($begintime) && !empty($endtime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), strtotime($endtime) + 60));
            } else if (!empty($begintime)) {
                $map['ctime'] = array('between', array(strtotime($begintime), time() + 60));
            } else if (!empty($endtime)) {
                $map['ctime'] = array('between', array(0, strtotime($endtime) + 60));
            }
        }
        if (!empty($keyword)) {
            $where['chat_withdrawals.order_no'] = array('eq', $keyword);
            $where['chat_userinfo.user_id'] = array('eq', $keyword);
            $where['chat_userinfo.user_phone'] = array('like', '%' . $keyword . '%');
            $where['chat_userinfo.user_name'] = array('like', '%' . $keyword . '%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }
        $viewModel = new ViewModel\WithdrawViewModel();
        $total = $viewModel->where($map)->count();
        $row = '10';
        $page = new Service\PageService($total, $row);
        $fpage = $page->fpage();
        $field = array(
            'id', 'user_uid', 'order_no', 'money', 'ratio', 'account', 'bank_name', 'bank_card_no', 'bank_card_holder', 'withdraw_phone', 'content', 'type', 'state', 'ctime', 'user_id', 'user_logo', 'user_name', 'user_sex', 'user_phone'
        );
        $data = $viewModel->where($map)->limit($page->listfirst, $page->listRows)->field($field)->order('ctime desc')->select();
        foreach ($data as $key => $value) {
//	    $data[$key]['money_text'] = (int) $data[$key]['money'];
            $data[$key]['money_text'] = '金币 ' . (int)$data[$key]['money'] . '<br /><label style="color:#ccc;">人民币 ' . sprintf('%.2f', ((int)$data[$key]['money'] / (int)$data[$key]['ratio'])) . '</label>';
            $data[$key]['type_text'] = $type_enum[$data[$key]['type']];
            $data[$key]['state_text'] = $state_enum[$data[$key]['state']];
            $user_info = $this->app_name2.'号：' . $data[$key]['user_id'] . '<br />用户昵称：' . $data[$key]['user_name'] . '<br />手机号码：' . $data[$key]['user_phone'];
            $data[$key]['user_info'] = $user_info;
            $account_info = $data[$key]['account'];
            if ($data[$key]['type'] == '3') {
                $account_info = '银行名称：' . $data[$key]['bank_name'] . '<br />银行卡号：' . $data[$key]['bank_card_no'] . '<br />持卡人：' . $data[$key]['bank_card_holder'] . '<br />联系方式：' . $data[$key]['withdraw_phone'];
            }
            $data[$key]['account_info'] = $account_info;
            $data[$key]['ctime'] = date('Y-m-d H:i', $data[$key]['ctime']);
        }
        $search = array('appsel' => $appcode, 'typesel' => $type, 'statesel' => $state, 'keyword' => $keyword, 'begintime' => $begintime, 'endtime' => $endtime);
        $this->assign(array(
            'moneytype' => $money_type,
            'data' => $data,
            'fpage' => $fpage,
            'total' => $total,
            'typearr' => $type_arr,
            'statearr' => $state_arr,
            'search' => $search,
            'app_code' => $app_code,
            'apparr' => $this->getapplist()
        ));
        $this->display();
    }

    public function finishsubmit()
    {
        $app_code = $this->app_code;
        $id = I('id');
        $content = I('content');
        $type = I('type');
        if (!empty($id)) {
            $map['id'] = $id;
            $model = M('chat_withdrawals');
            $data = $model->where($map)->find();
            $ration = $data['ratio'];
            if ($data) {
                $user_uid = $data['user_uid'];
                $money = (int)$data['money'];
                $order_no = $data['order_no'];
                $state = $type == '1' ? '2' : '3';
                $lab = $state == '2' ? '操作' : '驳回';
                $result = $model->where($map)->save(array('state' => $state, 'content' => $content, 'ptime' => time()));
                if ($result) {
                    $map = array();
                    $map['user_uid'] = $user_uid;
                    $model = M('chat_userwallet');
                    $data = $model->where($map)->find();
                    $totalBalance = $data['balance'];
                    if ($state == '2') {
//                        $user_id = M('chat_userinfo')->where(array('user_uid' => $user_uid))->getField('user_id');
//                        $data = array(
//                            'user_id' => $user_id,
//                            'user_uid' => $user_uid,
//                            'money' => $money,
//                            'type' => $data['type'],
//                            'state' => $data['state'],
//                            'order_no' => $data['order_no'],
//                            'account' => $data['account'],
//                            'bank_name' => $data['bank_name'],
//                            'bank_card_no' => $data['bank_card_no'],
//                            'bank_card_holder' => $data['bank_card_holder'],
//                        );
//                        $res = $this->withdrawremind($data);

                        //添加账户余额更新日志
                        $model = M('chat_balancelog');
                        $data = array(
                            'user_uid' => $user_uid,
                            'order_no' => $order_no,
                            'content' => '提现成功',
                            'money' => $money,
                            'balance' => $totalBalance,
                            'ratio' => $ration,
                            'state' => '1',
                            'type' => '4',
                            'toggle' => '1',
                            'ctime' => time(),
                            'app_flag' => $app_code,
                        );
                        $model->add($data);
                    }
                    if ($state == '3') {
                        $map = array();
                        $map['user_uid'] = $user_uid;
                        //退回到账户余额
//                        $model = M('chat_userwallet');
//                        $data = $model->where($map)->find();
//                        $balance = (int)$data['balance'] + (int)$money;
//                        newredisadd(33, "userwallet_" . $user_uid, 'balance', $balance);
//                        $model->where($map)->save(array('balance' => $balance));
//                        //添加账户余额更新日志
//                        $model = M('chat_balancelog');
//                        $data = array(
//                            'user_uid' => $user_uid,
//                            'order_no' => 'TX' . time() . rand(100000, 999999),
//                            'content' => '提现（订单号：' + $order_no + '）被管理员驳回',
//                            'money' => $money,
//                            'balance' => $totalBalance,
//                            'ratio' => '',
//                            'state' => '2',
//                            'type' => '4',
//                            'toggle' => '1',
//                            'ctime' => time(),
//                            'app_flag' => $app_code,
//                        );
//                        $model->add($data);
                    }
                    $response = array('ret' => '1001', 'code' => $lab . '成功！', 'data' => $state);
                } else {
                    $response = array('ret' => '1002', 'code' => $lab . '失败！', 'data' => $state);
                }
            } else {
                $response = array('ret' => '1002', 'code' => '对不起，该提现记录可能已被删除！');
            }
        } else {
            $response = array('ret' => '1002', 'code' => '无效的操作！');
        }
        $this->ajaxReturn($response, 'json');
    }

    /**
     * 手动添加充值记录
     */
    public function addrecharge()
    {
        if (!checkSuperAdmin()){
            $this->redirect('Finance/rechargelist', [], 2, '没有权限修改，跳转中…');
        }
        if (IS_POST) {

            //查询user_uid
            $chat_userinfo = M('chat_userinfo');
            $chat_userinfo_data = $chat_userinfo->where(['user_id' => I('user_id')])->field('user_uid')->find();
            if (empty($chat_userinfo_data)) {
                $response = array('ret' => '1002', 'code' => '对不起，改视频号无效！');
            } else {

                $user_uid = $chat_userinfo_data['user_uid'];
                //查询比率
                $sys_ratio = M('chat_systemset')->where(['app_flag' => I('app_flag')])->find();

                //更新钱包
                $chat_userwallet = M('chat_userwallet')->where(['user_uid' => $user_uid])->find();

                $balance = $chat_userwallet['balance'] + I('money');
                M('chat_userwallet')->where(['user_uid' => $user_uid])->save(['balance'=> $balance]);

                //记录充值表
                M('chat_recharge')->add([
                    'user_uid' => $user_uid,
                    'order_no' => I('app_flag') . time() . rand(200000, 999999),
                    'money' => I('money'),
                    'ratio' => (int)$sys_ratio['ratio'],
                    'type' => I('type'),
                    'ctime' => time(),
                    'app_flag' => I('app_flag'),
                ]);

                // 添加表格 banglog
                $balance_diff = I('money') * (int)$sys_ratio['ratio'];
                $data = array(
                    'user_uid' => $user_uid,
                    'order_no' => 'QT' . time() . rand(100000, 999999),
                    'content' => '管理员手动添加 ' . $balance_diff . ' 金币',
                    'money' => I('money'),
                    'balance' => $balance,
                    'ratio' => (int)$sys_ratio['ratio'],
                    'state' => '1',
                    'type' => '5',
                    'toggle' => '2',
                    'ctime' => time(),
                    'app_flag' => I('app_flag'),
                );
                M('chat_balancelog')->add($data);
                $response = array('ret' => '1001', 'code' => '成功！');

            }

            $this->ajaxReturn($response, 'json');

        }else {

            $this->assign(['apparr' => $this->getapplist()]);
            $this->display();
        }

    }
}
